<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/27 0027
 * Time: 14:41
 */

namespace app\admin\controller;
use app\common\logic\Draw;
use app\common\logic\DrawSec;
use app\common\logic\Explain;
use app\common\model\DrawRecord;
use app\common\model\Gift  as model;
use app\common\model\GiftRecord;
use app\common\service\DrawService;
use Carbon\Carbon;
use Qiniu\Auth;
use think\Db;

class Gift extends  Base
{

    public function  index()
    {

        $map=[];
        if(!empty($_GET['gift_name'])){
            $map['gift_name'] = ['like','%'.trim(input('get.gift_name')).'%'];
        }
        if(!isEmpty($_GET['status'])){
            $map['status']=trim(input('get.status'));
        }
        if(!isEmpty($_GET['type'])){
            $map['type']=trim(input('get.type'));
        }

        $model = new model();
        $rows  = $model->giftListAdmin($map);
        $this->assign([
            'rows'=>$rows,
            'pageHTML'=>$rows->render()
        ]);
        return view();
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 奖品列表
     */
    public function draw()
    {

        if (request()->isPost()){
            $model = new Draw();
            $price = input('post.price/a');
            $chance = input('post.chance/a');
            $remark = input('post.remark/a');
            $name = input('post.name/a');
            $id = input('post.id/a');
            foreach ($price as $k => $v){
                $data[$k]['id'] = $id[$k];
                $data[$k]['price'] = $v;
                $data[$k]['chance'] = $chance[$k];
                $data[$k]['remark'] = $remark[$k];
                $data[$k]['name'] = $name[$k];
            }
            $result = $model->change($data);
            if ($result) {
                DrawService::delete('draw');
                $this->success('修改成功');
            }
            $this->error($model->getError());
        }

        $rows = Db::name('draw')->where('status',1)->select();
        $map['status'] = 1;
        foreach ($rows as $k => $v){
            if ($v['type'] == 1){ //礼物
                $map['gift_id'] = $v['key'];
                $gift = Db::name('gift')->where($map)->find();
                if ($gift){
                    $rows[$k]['name']  = $gift['gift_name'];
                    $rows[$k]['price'] = $gift['price'];
                    $rows[$k]['img']   = $gift['thumbnail'];
                }else{
                    unset($rows[$k]);
                    Db::name('draw')->where('id',$v['id'])->delete();
                }
            }
        }

        $this->assign([
            'title' => '奖品列表',
            'rows' => $rows,
        ]);

        return view();

    }

    public function draw_sec()
    {

        if (request()->isPost()){
            $model = new DrawSec();
            $price = input('post.price/a');
            $chance = input('post.chance/a');
            $remark = input('post.remark/a');
            $name = input('post.name/a');
            $id = input('post.id/a');
            foreach ($price as $k => $v){
                $data[$k]['id'] = $id[$k];
                $data[$k]['price'] = $v;
                $data[$k]['chance'] = $chance[$k];
                $data[$k]['remark'] = $remark[$k];
                $data[$k]['name'] = $name[$k];
            }
            $result = $model->change($data);
            if ($result){
                DrawService::delete('draw_sec');
                $this->success('修改成功');
            }
            $this->error($model->getError());
        }

        $rows = Db::name('draw_sec')->where('status',1)->select();
        $map['status'] = 1;
        foreach ($rows as $k => $v){
            if ($v['type'] == 1){ //礼物
                $map['gift_id'] = $v['key'];
                $gift = Db::name('gift')->where($map)->find();
                if ($gift){
                    $rows[$k]['name']  = $gift['gift_name'];
                    $rows[$k]['price'] = $gift['price'];
                    $rows[$k]['img']   = $gift['thumbnail'];
                }else{
                    unset($rows[$k]);
                    Db::name('draw_sec')->where('id',$v['id'])->delete();
                }
            }
        }

        $this->assign([
            'title' => '奖品列表',
            'rows' => $rows,
        ]);

        return view();

    }
    /**
     * 中奖记录
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function draw_list()
    {


        $map = [];

        if(!empty(input('keyword'))){
            $map['u.nick_name|u.phone'] = ['like','%'.trim(input('keyword')).'%'];
            $where['u.nick_name|u.phone'] = ['like','%'.trim(input('keyword')).'%'];
        }
        if(!empty($_GET['uuid'])){
            $map['u.uuid'] = trim(input('get.uuid'));
        }
//        $hammer_num   = Db::name('users')->alias('u')->where($map)->sum('hammer_num');
//        $hammer_give  = Db::name('users')->alias('u')->where($map)->sum('hammer_give');


        if (!empty(input('startDate'))){
            if (empty(input('endDate'))){
                $map['a.create_time'] = ['> time',strtotime(input('startDate'))];
            }else{
                $map['a.create_time'] = ['between time',[strtotime(input('startDate')),strtotime(input('endDate').' 23:59:59')]];
            }
        }elseif (!empty(input('endDate'))){
            $map['a.create_time'] = ['<= time',strtotime(input('endDate').' 23:59:59')];
        }

        if (is_numeric(input('price'))){
            $map['a.price'] = ['>=',input('price')];
        }
//        dd($map);
        $model = new DrawRecord();
        $rows  = $model->getList($map);
        $total = $model->alias('a')
            ->join('users u','a.user_id = u.user_id','left')
            ->where($map)
            ->sum('total');
        $where['a.title'] = ['like','抽奖活动->%'];

        if ($where['u.nick_name|u.phone']){

            $use = Db::name('money_detail')
                ->alias('a')
                ->join('users u','a.user_id = u.user_id','left')
                ->where($where)
                ->sum('a.money');

        }else{

            $use = Db::name('money_detail')
                ->alias('a')
                ->where($where)
                ->sum('a.money');

        }

        //总抽奖次数
        $allNum = $model->alias('a')
            ->join('users u','a.user_id = u.user_id','left')
            ->where($map)
            ->sum('num');

        $this->assign([
//            'hammer_give' => $hammer_give,
//            'hammer_num'  => $hammer_num,
            'title'       => '中奖记录',
            'rows'        => $rows,
            'pageHTML'    => $rows->render(),
            'total'       => $total,
            'use'         => $use,
            'allNum'      => $allNum,
        ]);
        return view();
    }

    public function edit()
    {
        if (request()->isPost()){
            $data   = input('post.');
            $model  = new Draw();
            $result = $model->saveChange($data);
            if ($result !== false){
                $this->success('操作成功',url('draw'));
            }
            $this->error($model->getError());
        }
        $this->_find('draw');
        return view();
    }

    public function edit_sec()
    {
        if (request()->isPost()){
            $data   = input('post.');
            $model  = new DrawSec();
            $result = $model->saveChange($data);
            if ($result !== false){
                $this->success('操作成功',url('draw_sec'));
            }
            $this->error($model->getError());
        }
        $this->_find('draw_sec');
        return view();
    }


    //添加礼物类型
    public function  gift_edit()
    {
        $gift_id = input('id');

        if(request()->isPost())
        {
            $data  = request()->param();
            $map['type'] = 1;
            $map['key']  = $data['id'];

            $draw = Db::name('draw')->where($map)->find();
            $draw_sec = Db::name('draw_sec')->where($map)->find();;
            if ($data['is_draw'] == 1){ //参与抽奖
                $item['update_time'] = time();
                $item['chance'] = $data['chance'];
                $item['status'] = 1;
                if ($draw){
                    Db::name('draw')->where('id',$draw['id'])->update($item);
                }else{
                    $item['type'] = 1;
                    $item['key']  = $data['id'];
                    $item['create_time'] = time();
                    Db::name('draw')->insert($item);
                }
                $item['chance'] = $data['chance_sec'];
                if ($draw_sec){
                    Db::name('draw_sec')->where('id',$draw_sec['id'])->update($item);
                }else{
                    $item['type'] = 1;
                    $item['key']  = $data['id'];
                    $item['create_time'] = time();
                    Db::name('draw_sec')->insert($item);
                }

            }else{
                if ($draw){
                    $item['update_time'] = time();
                    $item['status'] = 0;
                    Db::name('draw')->where('id',$draw['id'])->update($item);
                }

                if ($draw_sec){
                    $item['update_time'] = time();
                    $item['status'] = 0;
                    Db::name('draw_sec')->where('id',$draw_sec['id'])->update($item);
                }
            }

            if($gift_id && $data['is_naming'] && (!$data['naming']))
            {
                $where['a.gift_id'] = $gift_id;
                $stat_time = Carbon::now()->startOfWeek()->timestamp;
                $where['a.create_time'] = ['between time', [$stat_time, time()]];
                $data['naming'] = GiftRecord::weekUser($where)->nick_name ?? '';
            }

            $model = new model();
            $model->saveChange($data)?$this->success('成功',url('index')):$this->error('失败');

        }

        $details = db('gift')->where('gift_id',$gift_id)->find();
        $domain = config('qiniu')['domain'];
        $auth  = new Auth(config('qiniu')['ACCESSKEY'], config('qiniu')['SECRETKEY']);
        $token = $auth->uploadToken(config('qiniu')['bucket']);
        $this->assign([
            'data' => $details,
            'token' => $token,
            'domain' => $domain,
        ]);

        return view();
    }

    public function  draw_del(){
        $id = input('id');
        if (!is_numeric($id)) $this->error('参数错误');
        $result = Db::name('draw')->where('id',$id)->delete();
        if ($result){
            $this->success('成功');
        }
        $this->error('失败');
    }

    public function  draw_del_sec(){
        $id = input('id');
        if (!is_numeric($id)) $this->error('参数错误');
        $result = Db::name('draw_sec')->where('id',$id)->delete();
        if ($result){
            $this->success('成功');
        }
        $this->error('失败');
    }

    //后台删除礼物
    public function  gift_delete(){
        $id = input('id');
        if (!is_numeric($id)) $this->error('参数错误');
        $result = Db::name('gift')->where('gift_id',$id)->delete();
        if ($result){
            $this->success('成功');
        }
        $this->error('失败');
    }

    //礼物赠送记录
    public  function  gift_record_list()
    {
        $map = [];
        if(!empty($_GET['gift_name'])){
            $map['g.gift_name'] = ['like','%'.trim(input('get.gift_name')).'%'];
        }
        if(!empty($_GET['startDate'])){
            $startDate = strtotime(trim(input('get.startDate')));
        }
        if(!empty($_GET['endDate'])){
            $endDate = strtotime(trim(input('get.endDate')));
        }
//        dd($startDate,$endDate);
        if($startDate&&$endDate){
            $map['gr.create_time'] = ['between',[$startDate,$endDate]];
        }else if($startDate&&empty($endDate)){
            $map['gr.create_time'] = ['>',$startDate];
        }else if($endDate&&empty($startDate)){
            $map['gr.create_time'] = ['<',$endDate];
        }

        if (is_numeric(input('room_id'))){
            $map['gr.room_id'] = input('room_id');
            $url = url('',['hash'=>hashid(input('room_id'))]);
        }else{
            $url = '';
        }

        if (!empty(input('hash'))){
            $map['gr.room_id'] = input('room_id');
        }

        if (is_numeric(input('user_id'))){
            $map['u.uuid'] = input('user_id');
        }
        if (is_numeric(input('to_user'))){
            $map['us.uuid'] = input('to_user');
        }

        $model = new GiftRecord();
        $rows  = $model->recordList($map);

        $total = $model->alias('gr')->where($map)
            ->join('gift g','gr.gift_id = g.gift_id','left')
            ->join('users u','gr.user_id = u.user_id','left')->sum('total');

        $this->assign([
            'rows'=>$rows,
            'pageHTML'=>$rows->render(),
            'total' => $total,
            'url' => $url,
        ]);
        return view();
    }
}